package com.guanzi.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guanzi.server.entity.Food;
import com.guanzi.server.entity.Order;
import com.guanzi.server.entity.Store;
import com.guanzi.server.entity.User;
import com.guanzi.server.entity.dto.OrderGenerateDTO;
import com.guanzi.server.entity.vo.OrderExcelVO;
import com.guanzi.server.entity.vo.StoreVO;
import com.guanzi.server.entity.vo.UserVO;
import com.guanzi.server.mapper.FoodMapper;
import com.guanzi.server.mapper.OrderMapper;
import com.guanzi.server.mapper.StoreMapper;
import com.guanzi.server.mapper.UserMapper;
import com.guanzi.server.query.OrderListQuery;
import com.guanzi.server.service.IOrderService;
import com.guanzi.server.util.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author guanzi
 * @since 2021-06-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private StoreMapper storeMapper;

    /**
     * 菜品下单
     * @param orderGenerateDTO
     */
    @Override
    public void generateOrder(OrderGenerateDTO orderGenerateDTO) {
        // 转换类型：菜品ID数组，总价格和当前用户ID
        int[] foodsId = Arrays.stream(orderGenerateDTO.getFoodIds()).mapToInt(Integer::parseInt).toArray();
        int price = Integer.parseInt(orderGenerateDTO.getTotalPrice());
        int currentUserId = Integer.parseInt(orderGenerateDTO.getUserId());
        // 所有的菜品只归属于一个商家，只查一次
        Food temp = foodMapper.selectById( foodsId[0] );
        Store s = storeMapper.selectById( temp.getEStoreId() );
        String foodName = "";
        for (int id : foodsId) {
            Food f = foodMapper.selectById(id);
            // 输出foodName
            foodName += f.getName() + "(" + f.getNumber() + ");";
            // 更新累计被点单数
            f.setCount(f.getCount() + 1);
            s.setCount(s.getCount() + 1);
            foodMapper.updateById(f);
            storeMapper.updateById(s);
        }
        // 去掉最后一个分号
        foodName = foodName.substring(0, foodName.length()-1);
        Order order = new Order();
        order.setEUserId(currentUserId);
        order.setEStoreId(s.getId());
        order.setCreateTime(LocalDateTime.now());
        order.setEndTime(LocalDateTime.now().plusMinutes(20));
        order.setFoodName(foodName);
        order.setRemark(order.getRemark());
        order.setPrice(price);
        baseMapper.insert(order);
    }

    /**
     * 订单列表展示（含分页）
     * @param orderListQuery
     */
    @Override
    public Pager<Order> getOrderList(OrderListQuery orderListQuery) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if ( orderListQuery.getUserData() != null && orderListQuery.getUserData() != "" ) {
            int userId = Integer.parseInt(orderListQuery.getUserData());
            if ( userId >= 0 ) {
                queryWrapper.eq("e_user_id", userId);
            }
        }
        if ( orderListQuery.getStoreData() != null && orderListQuery.getStoreData() != "" ) {
            int StoreId = Integer.parseInt(orderListQuery.getStoreData());
            if ( StoreId >= 0 ) {
                queryWrapper.eq("e_store_id", StoreId);
            }
        }
        if ( orderListQuery.getSearchKey() != "" && orderListQuery.getSearchKey() != null ) {
            String key = orderListQuery.getSearchKey();
            queryWrapper.like("food_name", key).or().like("remark", key);
        }
        // 前端的时间处理栏默认会处理开始和结束的顺序
        if ( orderListQuery.getStartTime() != null && orderListQuery.getStartTime() != "" && orderListQuery.getEndTime() != null && orderListQuery.getEndTime() != "") {
            // 默认有and
            queryWrapper.ge("createTime", orderListQuery.getStartTime()).le("endTime", orderListQuery.getEndTime());
        }
        IPage<Order> pageUtil = new Page<>(orderListQuery.getPage(), orderListQuery.getLimit());
        IPage<Order> p = baseMapper.selectPage(pageUtil, queryWrapper);
        // 处理返回的id，查询出对应的名称再放入分页
        for (Order record : p.getRecords()) {
            //取出record里面的userId和storeId，查询出对应的名称
            record.setEUserName( userMapper.selectOne(new QueryWrapper<User>().eq("id", record.getEUserId())).getUsername() );
            record.setEStoreName( storeMapper.selectOne(new QueryWrapper<Store>().eq("id", record.getEStoreId())).getName() );
        }

        return new Pager<>( (long)p.getRecords().size(), p.getRecords() );
    }

    /**
     * 获取订单中已有的用户信息
     * @return
     */
    @Override
    public List<UserVO> getUser() {
        // 查询出订单所有列表，再通过得到用户ID，在用户表里查出名称（注意需要去重）
        List<UserVO> list = baseMapper.selectUser();
        return list;
    }

    /**
     * 获取订单中已有的商家信息
     * @return
     */
    @Override
    public List<StoreVO> getStore() {
        // 查询出订单所有列表，再通过得到商家ID，在商家表里查出名称（注意需要去重）
        List<StoreVO> list = baseMapper.selectStore();
        return list;
    }

    /**
     * 获取将要导出的格式化订单信息
     *      虽然会报错，但是数据能传上去
     * @param list
     * @return
     */
    @Override
    public List<OrderExcelVO> getOutputValues(List<Order> list) {
        List<OrderExcelVO> orderExcelVOS = new ArrayList<>();
        // 判定是否存在同名，默认无
        boolean flag = false;
        for (Order order : list) {
            // 遍历每一条记录，取出菜品字段: 菜品名称（xx份）；菜品名称（xx份）；菜品名称（xx份）；菜品名称（xx份）...
            for( String foodName : order.getFoodName().split(";") ) {
                OrderExcelVO orderExcelVO = new OrderExcelVO();
                orderExcelVO.setFoodName(foodName.substring( 0, foodName.indexOf("(") ));
                orderExcelVO.setFoodNumber( Integer.parseInt(foodName.substring( foodName.indexOf("(")+1, foodName.lastIndexOf(")")) ));

                //遍历循环，如果已存在该菜名，则加数量
                for (OrderExcelVO excelVO : orderExcelVOS) {
                    if ( excelVO.getFoodName().equals(orderExcelVO.getFoodName()) ){
                        flag = true;
                        excelVO.setFoodNumber( orderExcelVO.getFoodNumber() + excelVO.getFoodNumber() );
                    }
                }
                // 循环完成发现没有同名的菜品，则添加
                if (!flag){
                    orderExcelVOS.add(orderExcelVO);
                }
                flag = false;
            }
        }
        return orderExcelVOS;
    }


}
